import { Model, DataTypes, Optional } from 'sequelize';
import sequelize from '@/config/database';

// 定义部门属性接口
interface DeptAttributes {
  deptId: number;
  parentId?: number;
  ancestors?: string;
  deptName: string;
  orderNum?: number;
  leader?: string;
  phone?: string;
  email?: string;
  status?: string;
  delFlag?: string;
  createBy?: string;
  createTime?: Date;
  updateBy?: string;
  updateTime?: Date;
  parentName?: string; // 父部门名称，非数据库字段
}

// 创建时可选的字段
interface DeptCreationAttributes extends Optional<DeptAttributes, 'deptId'> {}

// 部门模型类
class Dept extends Model<DeptAttributes, DeptCreationAttributes> implements DeptAttributes {
  public deptId!: number;
  public parentId?: number;
  public ancestors?: string;
  public deptName!: string;
  public orderNum?: number;
  public leader?: string;
  public phone?: string;
  public email?: string;
  public status?: string;
  public delFlag?: string;
  public createBy?: string;
  public createTime?: Date;
  public updateBy?: string;
  public updateTime?: Date;
  public parentName?: string; // 父部门名称，非数据库字段

  // 时间戳
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  // 用于树结构的子部门列表，不在数据库中存储
  public children?: Dept[];

  // 检查部门状态是否正常
  public isActive(): boolean {
    return this.status === '0' && this.delFlag === '0';
  }

  // 获取祖级列表数组
  public getAncestorsArray(): number[] {
    if (!this.ancestors) {
      return [];
    }
    return this.ancestors.split(',').map(id => parseInt(id));
  }

  // 判断是否为顶级部门
  public isTopDept(): boolean {
    return this.parentId === 0;
  }

  // 获取部门的所有子部门ID
  public static async getChildDeptIds(deptId: number): Promise<number[]> {
    const childDepts = await Dept.findAll({
      where: {
        parentId: deptId,
        delFlag: '0'
      }
    });
    
    const childIds = childDepts.map(dept => dept.deptId);
    
    // 递归获取所有子部门ID
    const subChildPromises = childDepts.map(dept => Dept.getChildDeptIds(dept.deptId));
    const subChildResults = await Promise.all(subChildPromises);
    
    // 合并所有子部门ID
    return [...childIds, ...subChildResults.flat()];
  }
}

Dept.init(
  {
    deptId: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      autoIncrement: true,
      field: 'dept_id',
      get() {
        // 确保返回数字类型
        const value = this.getDataValue('deptId');
        return value !== undefined ? Number(value) : undefined;
      }
    },
    parentId: {
      type: DataTypes.BIGINT,
      defaultValue: 0,
      field: 'parent_id',
      get() {
        // 确保返回数字类型
        const value = this.getDataValue('parentId');
        return value !== undefined ? Number(value) : undefined;
      }
    },
    ancestors: {
      type: DataTypes.STRING(50),
      defaultValue: '',
      field: 'ancestors'
    },
    deptName: {
      type: DataTypes.STRING(30),
      allowNull: false,
      field: 'dept_name'
    },
    orderNum: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      field: 'order_num',
      get() {
        // 确保返回数字类型
        const value = this.getDataValue('orderNum');
        return value !== undefined ? Number(value) : undefined;
      }
    },
    leader: {
      type: DataTypes.STRING(20),
      field: 'leader'
    },
    phone: {
      type: DataTypes.STRING(11),
      field: 'phone'
    },
    email: {
      type: DataTypes.STRING(50),
      field: 'email'
    },
    status: {
      type: DataTypes.CHAR(1),
      defaultValue: '0', // 0正常 1停用
      field: 'status'
    },
    delFlag: {
      type: DataTypes.CHAR(1),
      defaultValue: '0', // 0存在 2删除
      field: 'del_flag'
    },
    createBy: {
      type: DataTypes.STRING(64),
      field: 'create_by'
    },
    createTime: {
      type: DataTypes.DATE,
      field: 'create_time'
    },
    updateBy: {
      type: DataTypes.STRING(64),
      field: 'update_by'
    },
    updateTime: {
      type: DataTypes.DATE,
      field: 'update_time'
    }
  },
  {
    sequelize,
    tableName: 'sys_dept',
    timestamps: true,
    createdAt: 'createTime',
    updatedAt: 'updateTime',
  }
);

export default Dept; 